/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entities;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

/**
 *
 * @author Maciek
 */
public class DisciplineConverter implements Converter {
    private Session session;

    public Discipline getAsObject(FacesContext context, UIComponent component, String value) {
        Discipline dis = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Discipline where name='"+value+"'");
            System.out.println("????"+q.list().get(0));
            dis = (Discipline) q.list().get(0);
            for (int i=0; i<50; i++)
                System.out.println("????"+dis.getName()+" "+dis.getId());
            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return dis;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {
         String name = ((Discipline) value).getName();
         return name;
    }
}
